package com.yneusoft.manage.config;

import com.auth0.jwt.exceptions.SignatureVerificationException;
import com.auth0.jwt.exceptions.TokenExpiredException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.yneusoft.common.model.ResponseWrapper;
import com.yneusoft.common.tool.JwtTool;
import com.yneusoft.common.enums.ResultEnum;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * @author lt
 * @date 2021/10/26 10:28
 * @description: jwt拦截器设置（空、失效、签名错误、无效）
 */
@Slf4j
@Component
public class JwtTokenInterceptor implements HandlerInterceptor {
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        String token = request.getHeader("token");
        ResponseWrapper wrapper;
        if(!token.equals("token")){
            try {
                JwtTool.verify(token);
                log.info("token验证通过");
                return true;
            } catch (TokenExpiredException e) {
                log.warn("Token已经过期");
                wrapper = ResponseWrapper.markError(ResultEnum.TOKEN_TIMEOUT);
            } catch (SignatureVerificationException e) {
                log.error("Token签名错误");
                wrapper = ResponseWrapper.markError(ResultEnum.TOKEN_SIGN_ERROR);
            } catch (Exception e) {
                log.error("无效的token");
                wrapper = ResponseWrapper.markError(ResultEnum.TOKEN_ERROR);
                e.printStackTrace();
            }
        }
        else{
            log.error("token为空");
            wrapper = ResponseWrapper.markError(ResultEnum.AUTH_HEADER_NULL);
        }
        String json = new ObjectMapper().writeValueAsString(wrapper);
        response.setContentType("application/json;charset=UTF-8");
        response.getWriter().println(json);
        return false;
    }

}